package com.yunkaweilai.android.activity.operation.consumption.quick;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.lazylibrary.util.DensityUtil;
import com.github.lazylibrary.util.StringUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.MainActivity;
import com.yunkaweilai.android.activity.operation.consumption.ReceivablesActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.utils.ParseExpression;
import com.yunkaweilai.android.utils.TitleBuilder;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 计算器
 * Created by Administrator on 2017/7/11.
 */

public class CalculatorActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.id_tv_process)
    TextView idTvProcess;
    @BindView(R.id.id_tv_result)
    TextView idTvResult;
    @BindView(R.id.id_gridLayout)
    GridLayout idGridLayout;
    @BindView(R.id.id_btn_clean)
    Button idBtnClean;
    @BindView(R.id.id_btn_out)
    Button idBtnOut;
    @BindView(R.id.id_btn_checkout)
    Button idBtnCheckout;
    @BindView(R.id.id_llayout_bottom)
    LinearLayout idLlayoutBottom;


    private String[] btTexts = new String[]{
            "7","8","9","÷",
            "4", "5", "6", "×",
            "1", "2", "3", "-",
            "0", ".", "+", "=",
    };
    private int rowCount,cellWidth,columnCount,cellHeight;
    private GridLayout.LayoutParams cellParams,cellParams2;
    private GridLayout.LayoutParams tvParams,tvParams1;
    private int row;
    private int column;
    private GridLayout.Spec rowSpec;
    private GridLayout.Spec columnSpec;

    private Button bt;//点击事件的按钮
    private String btText;//点击的button的text
    private String resultString;
    private String regOperator = "\\+|-|×|÷";
    private String inputString;
    private String penultCharString;
    private String exp;
    private String expAndResult;
    private char lastChar = ' ';//最后一位输入的字符
    private String frontExp = exp;	//光标前的表达式,默认光标在尾端
    private String rearExp = "";	//光标后的表达式,默认光标在尾端
    private final static String ERROR = "格式错误";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator);
        ButterKnife.bind(this);
        new TitleBuilder(mAc).setTitleText("快速消费").setLeftImage(R.mipmap.ic_go_back)
        .setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent2Activity(MainActivity.class);
                finish();
            }
        });
        idBtnCheckout.setOnClickListener(this);
        idBtnOut.setOnClickListener(this);
        idBtnClean.setOnClickListener(this);
        initVal();
        initCalUI();
    }

    /**
     * 初始化赋值
     */
    private void initVal(){
        resultString = "";
        exp = "";
        expAndResult = "";
        frontExp = exp;
        rearExp = "";
        idTvProcess.setText("");
        idTvResult.setText("");
    }

    /**
     * 初始化计算器界面
     */
    private void initCalUI(){
        int[] deviceInfo = DensityUtil.getDeviceInfo(this);
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        int titielheight = DensityUtil.dip2px(mAc, 44);

        int mywidth = deviceInfo[0];
        int myHeight = 0;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P){
            myHeight = deviceInfo[1] - statusBarHeight1;
        }else {
            myHeight = deviceInfo[1] - statusBarHeight1 - titielheight;
        }

        Log.e("asd", "initCalUI: " + deviceInfo[0]+":" + deviceInfo[1]);
        rowCount = 7;
        columnCount = 4;
        cellWidth =  (mywidth - 3) / columnCount;
        cellHeight = (myHeight - 5) / rowCount ;
        tvParams = (GridLayout.LayoutParams)idTvProcess.getLayoutParams();
        tvParams.height = cellHeight;
        idTvProcess.setLayoutParams(tvParams);
        tvParams1 = (GridLayout.LayoutParams) idTvResult.getLayoutParams();
        tvParams1.height = cellHeight;
        idTvResult.setLayoutParams(tvParams1);
//        idGridLayout.setBackgroundColor(Color.parseColor("#D1D1D1"));
        //批量初始化按钮
        Button btn[] = new Button[btTexts.length];

        for(int i = 0; i < btTexts.length; i++){
            btn[i] = new Button(this);
            btn[i].setText(btTexts[i]);
            btn[i].setTextColor(getResources().getColor(R.color.wjx_content_txt_lighter_black));
            btn[i].setTextSize(30);
            btn[i].setBackgroundColor(Color.WHITE);
            row = i/columnCount + 2;
            column = i % columnCount;
            rowSpec = GridLayout.spec(row);
            columnSpec = GridLayout.spec(column);
            cellParams = new GridLayout.LayoutParams(rowSpec, columnSpec);
            cellParams.width = cellWidth;
            cellParams.height = cellHeight;
            if( column == (columnCount-1) )
                cellParams.setMargins(0, 1, 0, 0);
            else
                cellParams.setMargins(0, 1, 1, 0);
            idGridLayout.addView(btn[i], cellParams);
            btn[i].setBackgroundResource(R.drawable.btn_bg_selector_white);
            btn[i].setOnClickListener(this);
        }

    }

    @Override
    public void onClick(View v) {
        bt = (Button)v;
        btText = bt.getText().toString();
        exp = idTvProcess.getText().toString();
        expAndResult = "";
        frontExp = exp;
        rearExp = "";
        inputString = bt.getText().toString();

        if ( resultString.matches(ERROR) ){
            initVal();
        }


        if(btText.matches("[0-9]|\\+|-|×|÷|\\.|(\\( \\))|=")){
            //已经运算过一次并有了运算结果
            if((resultString != "")){
                if(ParseExpression.isOperator(inputString)){	//如果输入的是运算符，表明是继续运算
                    exp = resultString;
                    resultString = "";
                }
                else if(inputString.matches("=") ){	//若输入"="，继续重复上一次的运算符运算
                    exp = exp.replaceAll("\n=.*", "");
                    String[] op = ParseExpression.splitInfixExp(exp);
                    int opLen = op.length;
                    if (opLen >= 2){
                        exp = resultString + op[opLen - 2] + op[opLen - 1];
                    }
                    resultString = "";
                }
                else {	//重新开始新的运算
                    initVal();
                }
            }

            if ( inputString.matches("\\.") ) {
                if ( ParseExpression.appendDotValid(exp) ) {
                    if ( exp.matches(".*?(" + regOperator + "|\\()$|()") )
                        inputString = "0.";
                }
                else
                    return;

            }
            else{
                //输入为运算符
                if ( ParseExpression.isOperator(inputString) ) {

                    //如果lastCHar是运算符且倒数第二个字符是数字，则替换成input输入的运算符
                    if(exp.length() > 1){
                        lastChar = exp.charAt(exp.length()-1);
                        penultCharString = String.valueOf(exp.charAt(exp.length()-2));
                        if ( ParseExpression.isOperator(lastChar) ){
                            if(penultCharString.matches("[0-9]|\\)|\\.|%"))
                                exp = exp.substring(0, exp.length()-1);
                            else{
                                return;
                            }
                        }
                        else if ( (lastChar == '.')){
                            exp = exp.substring(0, exp.length()-1);
                        }
                    }
                    else if ( exp.length() == 1 ){
                        if( exp.matches("-") )
                            return;
                    }
                    else if( ! inputString.matches("-") )
                        return;
                }
                else if (inputString.matches("[0-9]")){
                    if( (exp.length() > 0) ){
                        lastChar = exp.charAt(exp.length()-1);
                        if( (lastChar == ')') || (lastChar == '%') )
                            return;
                    }
                    if(exp.endsWith("0")){
                        if(exp.length() == 1)
                            exp = "";
                        else
                            exp= exp.replaceAll("(.*?)(" + regOperator + "|\\()(0)$","$1$2");
                    }
                }
                lastChar = ' ';
            }

            if (inputString.equals("=")) {
                //若表达式以运算符结尾，则去掉末端的运算符 再执行运算
                exp = exp.replaceAll("(.*?)(\\+|-|×|÷)(\\(?)$", "$1");
                if( !ParseExpression.isParenthesisMatch(exp))
                    return;
                if( exp == "")
                    return;

                resultString = ParseExpression.calInfix(exp);
                expAndResult = exp;
                idTvResult.setText(resultString);
                idTvProcess.setText(expAndResult);
            }
            else {//每次点击按钮都走这部
                exp = exp + inputString;
                idTvProcess.setText("");
                idTvProcess.setText(exp);
//                idTvResult.setText(exp);
            }
        }
        else if(btText.matches("%")){
            if((resultString != "")){
                exp = resultString;
                resultString = "";
            }
            else if( !exp.matches(".*?(\\)|[0-9])$") ){
                return;
            }
            idTvProcess.setText(exp + "%");

        }

        else if(btText.matches("清空")){
            initVal();
            return;
        }

        else if(btText.matches("后退")){

            if (frontExp.equals(""))
                return;

            if(resultString != ""){
                initVal();
                return;
            }

            frontExp = frontExp.substring(0, frontExp.length()-1);
            idTvProcess.setText(frontExp + rearExp);
            return;
        }
        else if (btText.matches("结账")){
            if (StringUtils.isEmpty(idTvResult.getText().toString())){
                //若表达式以运算符结尾，则去掉末端的运算符 再执行运算
                exp = exp.replaceAll("(.*?)(\\+|-|×|÷)(\\(?)$", "$1");
                if( !ParseExpression.isParenthesisMatch(exp))
                    return;
                if( exp == "")
                    return;

                resultString = ParseExpression.calInfix(exp);
                expAndResult = exp;
                idTvResult.setText(resultString);
                idTvProcess.setText(expAndResult);
            }
            if ("格式错误".equals(idTvResult.getText().toString())){
                showToast("格式错误");
            }else{
                ReceivablesActivity.actionStart(mAc,idTvResult.getText().toString(),"", Api.CREATE_QUICK_ORDER);
            }


        }
    }
}
